import { useKeyPress } from 'ahooks'
import { useDispatch } from 'react-redux'
import {
  removeSelectComponent,
  changeComponentHidden,
  changeComponentLocked,
  copySelectComponent,
  pasteCopiedComponent,
  selectPrevComponent,
  selectNextComponent
} from '../store/componentsReducer'

function isActiveElementValid() {
  const activeElement = document.activeElement
  if (activeElement === document.body) return true
  return false
}

function useCanvaskeyPress() {
  const dispatch = useDispatch()

  useKeyPress(['backspace', 'delete'], () => {
    if (!isActiveElementValid()) return
    dispatch(removeSelectComponent())
  })

  useKeyPress(['ctrl.c', 'meta.c'], () => {
    if (!isActiveElementValid()) return
    dispatch(removeSelectComponent())
  })
  useKeyPress(['ctrl.v', 'meta.v'], () => {
    if (!isActiveElementValid()) return
    dispatch(pasteCopiedComponent())
  })

  useKeyPress('uparrow', () => {
    if (!isActiveElementValid()) return
    dispatch(selectPrevComponent())
  })

  useKeyPress('downarrow', () => {
    if (!isActiveElementValid()) return
    dispatch(selectNextComponent())
  })
}

export default useCanvaskeyPress
